/*
 * BackgroundImageShuffler - Wallpaper changer for Android
 * Copyright (C) 2011 Juhana Paavola <juhana.paavola@gmail.com>
 *
 * This file is part of BackgroundImageShuffler.
 *
 * BackgroundImageShuffler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * BackgroundImageShuffler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License
 * along with BackgroundImageShuffler.  If not, see <http://www.gnu.org/licenses/>.
*/
package com.juhanapaavola.widget;

import java.io.File;
import java.io.FileInputStream;
import java.util.Random;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.IBinder;
import android.provider.MediaStore;
import android.view.Display;
import android.view.WindowManager;

public class BISService extends Service {

	public static String FROM_CAMERA = Environment.DIRECTORY_DCIM;
	public static String FROM_ALL = "ALL";
	public static String FROM_NOTCAMERA = "NOTCAMERA";
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		changeImage(this, intent);		
		return START_NOT_STICKY;
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}


	FileInputStream getBitmapStream(File filename){
		FileInputStream fis = null;

		try {
			fis = new FileInputStream(filename);
		}catch (Exception e) {
			fis = null;
			e.printStackTrace();
		}
		return fis;
	}
	
	File[] getImageNames(Context context, boolean includeCamera){
		String[] projection = { MediaStore.Images.Media.DATA};
		Cursor curs = null;
		File[] ffiles = null;
		try{
			curs = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
			if(curs != null && curs.getCount()>0){		
				curs.moveToFirst();
				boolean next = true;
				boolean canAdd = false;
				int count = 0;
				File[] tmpfiles = new File[curs.getCount()];
				while(next){
					String path = curs.getString(curs.getColumnIndex(MediaStore.Images.Media.DATA));					
					String[] splitted = path.split("/");
					 
					boolean campic = false;
					campic = splitted[splitted.length-2].equalsIgnoreCase("camera");
																	
					if( campic && includeCamera){
						canAdd = true;
					}else if(!campic && includeCamera){
						canAdd = true;
					}else if(!campic && !includeCamera){
						canAdd = true;
					}else if(campic && !includeCamera){
						canAdd = false;
					}
										
					if(canAdd){
						tmpfiles[count] = new File(path);
						count++;
					}
					next = curs.moveToNext();
				}
				if(count>0)
					ffiles = tmpfiles;
			}
		}finally{
			curs.close();			
		}
		
		return ffiles;
	}
	
	void changeImage(Context context, Intent intent){		
		FileInputStream fis = null;		
		File dcim = null;
		String state = Environment.getExternalStorageState();
		File dcimFiles[] = null;
		
		if(Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) ){
			//prefs
			SharedPreferences prefs = context.getSharedPreferences(BISConfigure.PREF_NAME, 0);
			String pref_from = prefs.getString(BISConfigure.PREF_FROM, null);
			boolean resize = prefs.getBoolean(BISConfigure.PREF_RESIZE, false);
			boolean scale = prefs.getBoolean(BISConfigure.PREF_SCALE_DOWN, false);
			
			if(pref_from != null){				
				if(pref_from.equals(FROM_ALL)){
					dcimFiles = getImageNames(context, true);
				}else if(pref_from.equals(FROM_NOTCAMERA)){
					dcimFiles = getImageNames(context, false);
				}else if(pref_from.equals(FROM_CAMERA)){
					dcim = Environment.getExternalStoragePublicDirectory(pref_from);
					dcimFiles = dcim.listFiles();
					if(dcimFiles != null && dcimFiles.length > 0){
						for(File f:dcimFiles){
							if(f.getName().equalsIgnoreCase("camera") && f.isDirectory()){
								dcim = new File(dcim.getPath()+"/"+f.getName());
								dcimFiles = dcim.listFiles();
							}
						}
					}
				}				 
			}
			
			
			if(dcimFiles != null && dcimFiles.length>0){
				int seed = dcimFiles.length-1;
				int num = 0;
				int maxcount = dcimFiles.length-1;
				File filename = null;				
				Random rand = new Random();
				boolean found = false;
				
				if(BISProvider.mWallpaper == null)
					BISProvider.mWallpaper = new File("empty");
				
				while(!found){
					num = rand.nextInt(seed);
					filename = new File(dcimFiles[num].getPath());
					
					if(filename.isFile()){
						if(!filename.getPath().equals(BISProvider.mWallpaper.getPath())){
							BISProvider.mWallpaper = filename;
							found = true;
						}
					}
					
					if(maxcount > dcimFiles.length)
						found = true;
					else
						maxcount++;
				}
								
				if(BISProvider.mWallpaper.exists())
					fis = getBitmapStream(BISProvider.mWallpaper);
			}
			
			if(fis != null){
				if(resize){
					try{
						int w=0;
						int h = 0;
						Display disp = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
						w = disp.getWidth();
						h = disp.getHeight();
						Bitmap bm = BitmapFactory.decodeStream(fis);
						boolean bigger = false;
						
						if(bm.getWidth() > w && bm.getHeight() > h)
							bigger = true;
						
						if(scale && bigger){
							bm = Bitmap.createScaledBitmap(bm, w*2, h, true);							
						}else if(!scale){
							bm = Bitmap.createScaledBitmap(bm, w*2, h, true);
						}
							
						context.setWallpaper(bm);
					}catch (Exception e) {
						e.printStackTrace();
					}
				}else{
					try{
						context.setWallpaper(fis);
					}catch (Exception e) {
						e.printStackTrace();
					}
				}
			}			
		}
		
		stopService(intent);
	}

}
